package yunjiao.javatutorials.lang.concurrent;

import java.time.LocalDateTime;
import java.util.concurrent.*;

/**
 * 基础演示
 *
 * @author yangyunjiao
 */
public class ScheduledThreadPoolExecutorExample {
    public static void main(String[] args) throws InterruptedException {
        // 创建定时线程池
        ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(2);

        System.out.println("开始时间: " + LocalDateTime.now());

        // 1. 延迟执行一次
        ScheduledFuture<?> delayFuture = scheduler.schedule(
                () -> System.out.println("延迟5秒执行: " + LocalDateTime.now()),
                5, TimeUnit.SECONDS
        );

        // 2. 固定速率执行（不考虑任务执行时间）
        ScheduledFuture<?> fixedRateFuture = scheduler.scheduleAtFixedRate(
                () -> {
                    System.out.println("固定速率任务执行: " + LocalDateTime.now());
                    try {
                        Thread.sleep(1000); // 模拟任务执行时间
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                },
                2,  // 初始延迟
                3,  // 执行间隔
                TimeUnit.SECONDS
        );

        // 3. 固定延迟执行（考虑任务执行时间）
        ScheduledFuture<?> fixedDelayFuture = scheduler.scheduleWithFixedDelay(
                () -> {
                    System.out.println("固定延迟任务执行: " + LocalDateTime.now());
                    try {
                        Thread.sleep(2000); // 模拟任务执行时间
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                },
                2,  // 初始延迟
                3,  // 上次执行结束到下次执行开始的间隔
                TimeUnit.SECONDS
        );

        // 监控定时任务
        monitorScheduledTasks(scheduler, delayFuture, fixedRateFuture, fixedDelayFuture);

        // 运行30秒后关闭
        Thread.sleep(30000);

        // 取消任务
        fixedRateFuture.cancel(false);
        fixedDelayFuture.cancel(false);

        // 优雅关闭
        scheduler.shutdown();
        if (!scheduler.awaitTermination(10, TimeUnit.SECONDS)) {
            scheduler.shutdownNow();
        }
    }

    private static void monitorScheduledTasks(ScheduledThreadPoolExecutor scheduler,
                                              ScheduledFuture<?>... futures) {
        ScheduledExecutorService monitor = Executors.newSingleThreadScheduledExecutor();
        monitor.scheduleAtFixedRate(() -> {
            System.out.println("\n=== 定时任务状态 ===");
            System.out.println("活跃定时任务数: " + scheduler.getActiveCount());
            System.out.println("队列中的定时任务数: " + scheduler.getQueue().size());

            for (int i = 0; i < futures.length; i++) {
                System.out.println("任务" + i + " - 是否完成: " + futures[i].isDone() +
                        ", 是否取消: " + futures[i].isCancelled());
            }
        }, 0, 5, TimeUnit.SECONDS);

        // 监控25秒后关闭
        monitor.schedule(() -> monitor.shutdown(), 25, TimeUnit.SECONDS);
    }
}
